package cn.nfwx.tv.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;

import com.chiclam.android.receiver.ApkInstallReceiver;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseActivity;
import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.controller.AdvertiseController;
import cn.nfwx.tv.controller.BusAnimController;
import cn.nfwx.tv.controller.MovementController;
import cn.nfwx.tv.controller.player.BasePlayerController;
import cn.nfwx.tv.controller.player.BusPlayerController;
import cn.nfwx.tv.controller.player.LivePlayerController;
import cn.nfwx.tv.db.AppDatabase;
import cn.nfwx.tv.events.AppointEvent;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.fragment.bus.BusSceneFragment;
import cn.nfwx.tv.fragment.callback.ActionCallback;
import cn.nfwx.tv.fragment.dialog.WifiNoteFragment;
import cn.nfwx.tv.fragment.dialog.WifiSelectDialogFragment;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.LocationHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.UmengPushHelper;
import cn.nfwx.tv.manager.NFWXWiFiManager;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.NetworkUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.util.WifiSupport;
import cn.nfwx.tv.widget.ShineImage;
import cn.nfwx.tv.widget.nfwxplayer.NfwxVideoPlayer;
import cn.nfwx.tv.widget.nfwxplayer.NfwxVideoPlayerManager;

public class HomeActivity extends BaseActivity implements NetworkHelper.NetworkStateListener, NFWXWiFiManager.OnWiFiAvailableListener, WifiNoteFragment.onWifiNoteClick, ActionCallback {

    private final static String TAG_LOG = "HomeActivity";

    private NfwxVideoPlayer nvp_player;

    // 统计
    private boolean isBusScene = false;

    private boolean isBusSceneLeave = false;
    private boolean isBusSceneIn = false;

    private boolean isBusInBackground = false;

    private InnerRecevier innerReceiver;
    private ApkInstallReceiver apkInstallReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtil.e(TAG_LOG, "onCreate");
        super.onCreate(savedInstanceState);


        EventBus.getDefault().register(this);

        UmengPushHelper.getInstance().setDayTag();
        NetworkHelper.getInstance().addListener(this);

        initView();
        loadData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_player2;
    }

    private void initView() {
        nvp_player = findViewById(R.id.nvp_player);
        nvp_player.setPlayerType(NfwxVideoPlayer.TYPE_IJK);
        if (WifiSupport.isWifiEnable(this)) {//连接的是wifi
            if (WifiSupport.getConnectedWifiInfo(this).getSSID().contains("广州公交免费wifi")) {//连接的是公交的wifi
                isBusScene = true;
                openBusController();
            } else {
                openLiveController();
            }
        } else {
            openLiveController();
        }
    }

    /**
     * 打开公交模式
     */
    private void openBusController() {
        if (nvp_player.getController() instanceof BusPlayerController) {
            return;
        }
        BasePlayerController controller = new BusPlayerController(this);
        ShineImage loading = new ShineImage(this);
        controller.setLoadingView(loading, 0, 0);
        nvp_player.setController(controller);
    }

    /**
     * 打开普通播放模式
     */
    private void openLiveController() {
        if (nvp_player.getController() instanceof LivePlayerController) {
            return;
        }
        BasePlayerController controller = new LivePlayerController(this);
        ShineImage loading = new ShineImage(this);
        controller.setLoadingView(loading, 0, 0);
        nvp_player.setController(controller);
    }

    /**
     * 离开公交场景
     */
    private void busSceneLeave() {
        if (isBusScene) {
            if (isBusInBackground) {
                isBusSceneIn = false;
                isBusSceneLeave = true;
                isBusScene = true;
            } else {
                BusAnimController.leaveBus(getSupportFragmentManager(), new BusSceneFragment.OnAnimationFinishListener() {
                    @Override
                    public void onStart() {
                        isBusScene = false;
                        openLiveController();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
            }
        }
    }

    /**
     * 进入公交场景
     */
    private void busSceneIn() {
        if (isBusInBackground) {
            isBusSceneIn = true;
            isBusSceneLeave = false;
            isBusScene = true;
        } else {
            BusAnimController.intBus(getSupportFragmentManager(), new BusSceneFragment.OnAnimationFinishListener() {
                @Override
                public void onStart() {
                    isBusScene = true;
                    openBusController();
                }

                @Override
                public void onFinish() {

                }
            });
        }
    }

    /**
     * 获取需要获取的信息
     */
    private void loadData() {
        AdvertiseController.getInstance().loadAdvertiseList(this);
        AccountHelper.getInstance().checkIjkUpdate(this);
        MovementController.getInstance().loadData(this, getSupportFragmentManager());
        AccountHelper.getInstance().refreshDaoAppoint(this, this.<Boolean>bindToLifecycle(), null);
        AccountHelper.getInstance().requestIp(this);

        if (innerReceiver == null) {
            innerReceiver = new InnerRecevier();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
            registerReceiver(innerReceiver, intentFilter);
        }

        if (apkInstallReceiver == null) {
            apkInstallReceiver = new ApkInstallReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
            intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            registerReceiver(apkInstallReceiver, intentFilter);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Toast.makeText(this, "requestCode=" + requestCode, Toast.LENGTH_SHORT).show();
        switch (requestCode) {
            case 401: {
                if (AndPermission.hasPermissions(this
                        , Manifest.permission.ACCESS_NETWORK_STATE
                        , Manifest.permission.CHANGE_NETWORK_STATE
                        , Manifest.permission.CHANGE_WIFI_STATE
                        , Manifest.permission.ACCESS_WIFI_STATE)) {
                    //WifiHelper.startScan(this);
                }
                break;
            }
            default:
                break;
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        MineFragment mineFragment = (MineFragment) DialogFragmentHelper.getFragment(getSupportFragmentManager(), "mineFragment");
        if (mineFragment != null) {
            mineFragment.dismiss();
        } else {
            this.callbackByfragment(CcpActivity.ACTION_RELOAD_CHANNEL, null);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void playEventBus(PlayEvents events) {
        MineFragment mineFragment = (MineFragment) DialogFragmentHelper.getFragment(getSupportFragmentManager(), "mineFragment");
        if (mineFragment != null) {
            mineFragment.dismiss();
        }
        nvp_player.playEventBus(events);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerAppiontEvent(final AppointEvent event) {
        nvp_player.appiontEvent(event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isBusInBackground = true;
        if (nvp_player != null && (nvp_player.isPlaying() || nvp_player.isBufferingPlaying())) {
            nvp_player.pause();
        }
    }

    @Override
    protected String activityName() {
        return HomeActivity.class.getSimpleName();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isBusInBackground) {
            isBusInBackground = false;
            if (isBusSceneIn) {
                busSceneIn();
            } else if (isBusSceneLeave) {
                busSceneLeave();
            }
        }
        if (!nvp_player.isClipPause() && !nvp_player.isHandPause()) {
            if (nvp_player != null && (nvp_player.isPaused() || nvp_player.isBufferingPaused() || nvp_player.isIdle())) {
                nvp_player.reStart();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        NetworkHelper.getInstance().removeListener(this);

        SharePrefUtil.save4gstautus(this, false);

        EventBus.getDefault().unregister(this);

        // 清除所有计算
        UmengPushHelper.getInstance().releaseTag();

        BusAnimController.getInstance().release();

        NfwxVideoPlayerManager.instance().releaseVideoPlayer();

        if (innerReceiver != null) {
            unregisterReceiver(innerReceiver);
        }

        if (apkInstallReceiver != null) {
            unregisterReceiver(apkInstallReceiver);
        }

        NFWXApplication.getInstance().getIwxapi().unregisterApp();
        AppDatabase.getInstance(mContext).closeDb();

        LocationHelper.getInstance().stop();

        ThreadHelper.destroy();
    }

    @Override
    public void onBackPressed() {
        if (nvp_player.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    public void callbackByfragment(String action, Bundle bundle) {
        nvp_player.getController().callbackByfragment(action, bundle);
    }

    class InnerRecevier extends BroadcastReceiver {
        static final String SYSTEM_DIALOG_REASON_KEY = "reason";
        static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                        if (isBusInBackground) {
                            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                        }
                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                        if (isBusInBackground) {
                            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                        }
                    }
                }
            } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                nvp_player.onReceive(intent);
            }
        }
    }

    @Override
    public void onNetworkChange(int networkType) {
        if (networkType == NetworkUtil.NO_NETWORK) {
            busSceneLeave();
        } else if (networkType == NetworkUtil.G_NETWORK) {
            busSceneLeave();
        } else if (networkType == NetworkUtil.WIFI_NETWORK ||
                networkType == NetworkUtil.LINE_NETWORK) {
            if (WifiSupport.getConnectedWifiInfo(mContext).getSSID().contains("广州公交免费wifi")) {
                busSceneIn();
            } else {
                openLiveController();
            }
        }
        nvp_player.onNetworkChange(networkType);
    }

    @Override
    public void onWiFiAvailable(final List<String> wifis) {
        //DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DialogFragmentHelper.removeFragment(getSupportFragmentManager(), "wifinote");
                if (wifis == null || wifis.isEmpty()) {
                    return;
                }
                ArrayList<String> wifi = new ArrayList<String>();
                wifi.addAll(wifis);
                WifiSelectDialogFragment wifiSelectDialogFragment = WifiSelectDialogFragment.newInstance(wifi);
                DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), wifiSelectDialogFragment);
            }
        });
    }

    @Override
    public void onNoWiFi() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(getSupportFragmentManager(), "wifinote");
                if (fragment == null) {
                    WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(2);
                    wifiNoteFragment.setOnWifiNoteClick(HomeActivity.this);
                    DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), wifiNoteFragment, "wifinote");
                } else {
                    fragment.loadFailure();
                }
            }
        });
    }

    @Override
    public void onWiFiConnected() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DialogFragmentHelper.removeFragment(getSupportFragmentManager(), "wifinote");
            }
        });
    }

    @Override
    public void wifiNoEnable() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(getSupportFragmentManager(), "wifinote");
                if (fragment == null) {
                    WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(2);
                    wifiNoteFragment.setOnWifiNoteClick(HomeActivity.this);
                    DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), wifiNoteFragment, "wifinote");
                } else {
                    fragment.loadFailure();
                }

                ToastUtil.show(mContext, R.string.wifi_open_error);
            }
        });
    }

    @Override
    public void tryagain() {
        WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(getSupportFragmentManager(), "wifinote");
        if (fragment == null) {
            WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(1);
            wifiNoteFragment.setOnWifiNoteClick(this);
            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), wifiNoteFragment, "wifinote");
        } else {
            fragment.setOnWifiNoteClick(this);
            fragment.loadLoading();
        }
        ThreadHelper.postDelayed(new Runnable() {
            @Override
            public void run() {
                //WifiHelper.startScan(HomeActivity.this);
            }
        }, 1000);
    }
}
